<?php

require_once dirname(__FILE__) . '/../lib/questionaireGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/questionaireGeneratorHelper.class.php';

/**
 * questionaire actions.
 *
 * @package    Attitude Orchestra
 * @subpackage questionaire
 * @author     Attitude OÜ
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class questionaireActions extends autoQuestionaireActions {

    public function executeNew(sfWebRequest $request) {
        $this->setLayout('popuplayout');

        parent::executeNew($request);
    }
    
    public function executeCopy(sfWebRequest $request)
    {
      $questionaire = Doctrine::getTable('Questionaire')->find($request->getParameter('id'));
      
      if($questionaire) {
        # copy product main information
        $newProduct = $questionaire->copy();
        
        $newProduct->setAnsweredCt(0);
        $newProduct->setIsActive(0);
        $newProduct->setStructureId(null);

        ## copy product Translations
        $transArr = $questionaire->Translation->toArray();
        
        foreach ($transArr as $index => &$transVal) {
            $transVal['name'] .= '_copy_' . rand(10000, 99999);
            unset($transVal['id']);
        }

        $newProduct->Translation->fromArray($transArr);

        $newProduct->save();
        
        // Getting last insert ID
        $last_id = $newProduct->getId();
        
        if($last_id) {
          $questions = Doctrine::getTable('Question')->createQuery('q')
            ->innerJoin('q.Answers a')
            ->execute();
          
          foreach($questions as $question) {
            $q = new Question();
            
            $q->setName($question->getName());
            $q->setAnswerType($question->getAnswerType());
            $q->setRequired($question->getRequired());
            $q->setQuestionaireId($last_id);
            
            $q->save();
            
            if($question->getAnswers()) {
              foreach($question->getAnswers() as $answer) {
                $a = new Answer();
                
                $a->setLabel($answer->getLabel());
                $a->setQuestionId($q->getId());
                
                $a->save();
              }
            }
          }
        }
      }
      
      $this->setLayout(false);
      $this->redirect('questionaire/edit?id='.$request->getParameter('id'));
      
      return sfView::NONE;
    }

    public function executeEdit(sfWebRequest $request) {
        $this->setLayout('popuplayout');

        parent::executeEdit($request);
    }

    public function executeCreate(sfWebRequest $request) {
        $this->setLayout('popuplayout');

        parent::executeCreate($request);
    }

    public function executeUpdate(sfWebRequest $request) {
        $this->setLayout('popuplayout');
        $this->setTemplate('edit');

        parent::executeUpdate($request);
    }
    
    public function executeChangeStatus(sfWebRequest $request) {
        $this->setLayout(false);
        
        $status = $request->getParameter('status');
        $id = $request->getParameter('id');
        
        $quest = QuestionaireTable::getInstance()->find($id);
        $quest->setIsActive($status);
        
        if ($status == 1) {
            $dt = new DateTime();
            $quest->setActiveFrom($dt->format('Y-m-d H:i:s'));
        }
        
        $quest->save();
        
        return sfView::NONE;
    }

    public function executeQuestions(sfWebRequest $request) {
        $this->setLayout('popuplayout');

        $this->form = new embedQuestionsForm();
        $this->qId = $request->getParameter('id');
        $this->questionaire = QuestionaireTable::getInstance()->find($this->qId);

        if ($request->getMethod() == 'POST' && 
            $questions = $request->getParameter('questions')) {
            
            $this->saveQuestions($questions);
        }

        $qs = $this->questionaire->getQuestions();
        $this->form->embedForm('questions', $this->prepQuestionsForm($qs));
    }
    
    public function executeDeleteQuestion(sfWebRequest $request) {
        $this->setLayout(false);
        
        if ($id = $request->getParameter('id')) {
            QuestionTable::getInstance()->find($id)->delete();
                    
            return sfView::NONE;
        }        
    }
    
    public function executeAnswers(sfWebRequest $request) {
        $this->setLayout('popuplayout');

        $this->qId = $request->getParameter('id');
        $this->questionaire = QuestionaireTable::getInstance()->find($this->qId);
        $this->questions = $this->questionaire->getQuestions();
        $this->selQuestion = false;
                
        $this->form = new sfForm();
        
        if ($questionId = $request->getParameter('question_id')) {
            $this->selQuestion = QuestionTable::getInstance()->find($questionId);
            
            if ($request->getMethod() == 'POST') {
                $answers = $request->getParameter('answers');
                $this->saveAnswers($answers);
            }

            $answers = $this->selQuestion->getAnswers();
            
            $this->form->embedForm('answers', $this->prepAnswersForm($answers));
        }
        
        /**
         * Fetch count to indicate
         */
        $this->answers = array();
        
        foreach($this->questions as $quons) {
          $this->answers[$quons->getId()] = Doctrine::getTable('Answer')->createQuery('a')
            ->select('count(id)')
            ->where('a.question_id 	 = ?', $quons->getId())
            ->fetchArray();
          
          $this->answers[$quons->getId()] = $this->answers[$quons->getId()][0]['count'];
        }
    }
    
    public function executeDeleteAnswer(sfWebRequest $request) {
        $this->setLayout(false);
        
        if ($id = $request->getParameter('id')) {
            AnswerTable::getInstance()->find($id)->delete();
                    
            return sfView::NONE;
        }             
    }
    
    public function executeResults(sfWebRequest $request) {
        $this->setLayout('popuplayout');
        
        $this->qId = $request->getParameter('id');
        $this->questionaire = QuestionaireTable::getInstance()->find($this->qId);
        
        $this->results = $this->questionaire->getResults();
        $this->selResult = false;
        
        if ($resultId = $request->getParameter('result_id')) {
            $this->selResult = ResultTable::getInstance()->find($resultId);
        }
    }
    
    public function executeExport(sfWebRequest $request) {
        $this->setLayout(false);
        
        $this->qId = $request->getParameter('id');
        $this->questionaire = QuestionaireTable::getInstance()->find($this->qId);
        $this->defaults = array(
                    array('Ees-ja perenimi', ''),
                    array('Sugu', 'Mees/Naine'),
                    array('Emakeel', 'Eesti/Vene/Inglise'),
                    array('Elukoha aadress', ''),
                    array('E-posti aadress', ''),
                    array('Kontakttelefon', ''),
                    array('Haridus', 'Gümnaasium/Bakalaurus/Magister/Doktor'),
                    array('Vanus', '18-25/26-35/36-45/46-55/56-65')
                );
        
        
        $query = Doctrine::getTable('ResultUser')->createQuery('ru')
          ->innerJoin('ru.Results r')
          ->innerJoin('r.Answers a')
          ->where('r.questionaire_id = ?', $request->getParameter('id'))
          ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY)
          ->execute();
        
        
        $csv = array();
        $exp = '/[0-9]+? : ([^\r\n]*)/is';
        
        // Place information into array
        foreach($query as $j => $user) {
          $csv[$j][] = $user['firstname'] . ' ' . $user['lastname'];
          $csv[$j][] = $user['sex'];
          $csv[$j][] = $user['native_language'];
          $csv[$j][] = $user['remote_addr'];
          $csv[$j][] = $user['address'];
          $csv[$j][] = $user['email'];
          $csv[$j][] = $user['phone'];
          $csv[$j][] = $user['education'];
          $csv[$j][] = $user['age'];
          
          foreach($user['Results'][0]['Answers'] as $answer) {
            $csv[$j][] = $answer['question'];
            
            if(preg_match_all($exp, $answer['answer'], $output)) {
              foreach($output[1] as $aw) {
                $csv[$j][] = $aw;
              }
            } else {
              $csv[$j][] = $answer['answer'];
            }
          }
        }
        
        
        // echo '<pre>';
        // print_r($csv);
        // exit;
        // exit;
        require_once dirname(__FILE__) . '/../lib/excel.class.php';
        
        $xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
        $xls->addArray($csv);
        $xls->generateXML(oxtSluggableTranslit::urlize($this->questionaire->getStructure()->getTitle()).'_export.csv');
        
        exit;
        
        /*$this->lines = array();
        
        foreach($csv as $line) {
          $this->lines[] = implode(';', $line);
        }
        
        // Final stage
        $this->lines = implode("\r\n", $this->lines);
        
        // Replace estonian letters
        $this->lines = str_replace(array('ü', 'õ', 'ä'), array('u', 'o', 'a'),  $this->lines);
        
	      $this->getResponse()->clearHttpHeaders();
	      $this->getResponse()->setHttpHeader('Content-Type', 'application/vnd.ms-excel; charset=UTF-8LE');
	      $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.oxtSluggableTranslit::urlize($this->questionaire->getStructure()->getTitle()).'_export.csv"'); */          
    }
    
    private function prepAnswersForm($answers) {
        $form = new sfForm();
        foreach ($answers as $k => $a) {
            $sub = new AnswerForm($a);
            $form->embedForm($k, $sub);
        }
        $k = isset($k) ? $k : -1;
        $sub = new AnswerForm();
        $form->embedForm($k + 1, $sub);

        return $form;        
    }

    private function prepQuestionsForm($questions) {
        $form = new sfForm();
        foreach ($questions as $k => $q) {
            $sub = new QuestionForm($q);
            $form->embedForm($k, $sub);
        }
        $k = isset($k) ? $k : -1;
        $sub = new QuestionForm();
        $form->embedForm($k + 1, $sub);

        return $form;
    }
    
    
    private function saveAnswers($answers) {
        foreach ($answers as $a) {
            if (isset($a['id']) && $a['id'] != '') {
                $answer = AnswerTable::getInstance()->find($a['id']);
            } else {
                $answer = new Answer();
                $answer->setQuestion($this->selQuestion);
            }

            if ($a['label'] != '') {
                $answer->setLabel($a['label']);
                $answer->save();
            }
        }
    }    

    private function saveQuestions($questions) {
        foreach ($questions as $q) {
            if (isset($q['id']) && $q['id'] != '') {
                $question = QuestionTable::getInstance()->find($q['id']);
            } else {
                $question = new Question();
                $question->setQuestionaire($this->questionaire);
            }

            if ($q['name'] != '') {
                $question->setName($q['name']);
                $question->setAnswerType($q['answer_type']);
                $question->setRequired(isset($q['required']));
                $question->save();
            }
        }
    }

}
